<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/25 0025
 * Time: 10:00
 */

namespace Cohuna\Services;

use Cohuna\Models\CohunaOrder;
use Cohuna\Models\CohunaOrderDetail;
use Cohuna\Models\CohunaPay;
use Phalcon\Di;

class CohunaOrderService extends ServiceBase
{
    /**
     * @var static
     */
    protected static $instance = null;

    /**
     * 创建支付订单
     * @param array $params
     * @return bool|CohunaOrder
     * @throws \Exception
     */
    public function createOrder(array $params)
    {
        if(empty($params['order_no'])){
            throw new \Exception('订单号不能为空');
        }
        if(empty($params['pay_id'])){
            throw new \Exception('支付编号不能为空');
        }
        if(empty($params['order_subject']) || strlen($params['order_subject']) > 500){
            throw new \Exception('订单标题不能为空且必须小于500字符');
        }
        if(!isset($params['total_amount']) || bccomp($params['total_amount'],'0',2) <= 0){
            throw new \Exception('订单金额必须大于0');
        }
        if(!isset($params['mch_id']) || empty($params['mch_id'])){
            throw new \Exception('商户号不能为空');
        }

        $pay = CohunaPay::findFirst(array("pay_id = :pay_id: AND is_delete = 0 AND pay_status = 'y'",'bind'=>array('pay_id'=>$params['pay_id'])));
        if(empty($pay)  ){
            throw new \Exception('不支持的支付方式');
        }
        $channel_list = Di::getDefault()->getShared('config')->payment_platform_list[$pay->pay_platform]['gateway_list'][$pay->gateway]['channel']->toArray();

        if(!isset($params['trade_channel']) || !in_array($params['trade_channel'],$channel_list)){
            throw new \Exception('不支持的交易渠道');
        }

        $cohuna_order = CohunaOrder::findFirst(array(
            'order_no = :order_no: AND merchant_id = :merchant_id:',
            'bind' => array(
                'order_no' => $params['order_no'],
                'merchant_id' => $params['mch_id']
            )
        ));

        if(empty($cohuna_order)){
            $cohuna_order = new CohunaOrder();
        }else{
            return $cohuna_order;
        }
        $this->db->begin();

        $cohuna_order->transaction_id   = CommonService::getInstance()->createSerialNumber();
        $cohuna_order->order_no         = $params['order_no'];
        $cohuna_order->merchant_id      = $params['mch_id'];
        $cohuna_order->pay_id           = $params['pay_id'];
        $cohuna_order->trade_state      = 'NOTPAY';
        $cohuna_order->order_subject    = $params['order_subject'];
        $cohuna_order->total_amount     = $params['total_amount'];
        $cohuna_order->trade_channel    = $params['trade_channel'];
        $cohuna_order->time_start       = date('Y-m-d H:i:s');

        $cohuna_order->body             = isset($params['body']) ? $params['body'] : null;
        $cohuna_order->buyer_id         = isset($params['buyer_id']) ? $params['buyer_id'] : null;
        $cohuna_order->seller_id        = isset($params['seller_id']) ? $params['seller_id'] : null;
        $cohuna_order->discount_amount  = isset($params['discount_amount']) ? $params['discount_amount'] : null;
        $cohuna_order->operator_id      = isset($params['operator_id']) ? $params['operator_id'] : null;
        $cohuna_order->store_id         = isset($params['store_id']) ? $params['store_id'] : null;
        $cohuna_order->terminal_id      = isset($params['terminal_id']) ? $params['terminal_id'] : null;
        $cohuna_order->attach           = isset($params['attach']) ? $params['attach'] : null;
        $cohuna_order->currency         = isset($params['currency']) ? $params['currency'] : 'CNY';
        $cohuna_order->notify_url       = isset($params['notify_url']) ? $params['notify_url'] : null;
        $cohuna_order->time_expire      = isset($params['time_expire']) ? $params['time_expire'] : date('Y-m-d H:i:s',time() + 90 * 60);

        if(!$cohuna_order->create()){
            $this->db->rollback();
            return false;
        }
        if(isset($params['goods_detail']) && is_array($params['goods_detail'])) {
            foreach ($params['goods_detail'] as $goods) {
                if (empty($goods['goods_id']) || strlen($goods['goods_id']) > 50) {
                    $this->db->rollback();
                    throw new \Exception('订单商品参数【goods_id】异常');
                }
                if (empty($goods['goods_name']) || strlen($goods['goods_name']) > 300) {
                    $this->db->rollback();
                    throw new \Exception('订单商品参数【goods_name】异常');
                }
                if (empty($goods['price']) || bccomp($goods['price'], 0) <= 0) {
                    $this->db->rollback();
                    throw new \Exception('订单商品参数【price】异常');
                }

                $order_detail = new CohunaOrderDetail();
                $order_detail->merchant_id = $params['mch_id'];
                $order_detail->order_no = $params['order_no'];
                $order_detail->goods_id = $goods['goods_id'];
                $order_detail->goods_name = $goods['goods_name'];
                $order_detail->quantity = $goods['quantity'];
                $order_detail->price = $goods['price'];
                $order_detail->goods_category = isset($goods['goods_category']) ? $goods['goods_category'] : null;
                $order_detail->body = isset($goods['body']) ? $goods['body'] : null;
                $order_detail->show_url = isset($goods['show_url']) ? $goods['show_url'] : null;
                $order_detail->image_url = isset($goods['image_url']) ? $goods['image_url'] : null;
                if (!$order_detail->create()) {
                    $this->db->rollback();
                    return false;
                }
            }
        }
        if($this->db->commit()){
            return $cohuna_order;
        }
        return false;
    }
}